<?php

class Util {
	static public function MemcacheInit() {
		global $G;
		foreach ($G['memcache_opts']['servers'] as $mcserver) {
			$G['memcache']->addServer($mcserver, $G['memcache_opts']['port'], true); // add as a persistent connection
		}
	}

	static public function ItIsDowntime() {
		global $G;
		$cur_hm = date('Gi');
		$cur_hm_range = range($G['downtime']['start_time'], $G['downtime']['end_time']);
		return ($G['downtime']['enable_downtime'] == 1 && in_array($cur_hm, $cur_hm_range));
	}

	static public function parse_real_ip_from_xff($xff, $ip) {
		$return = false;
		$ips = explode(',', $xff);

		if (!empty($ip))
			array_unshift($ips, $ip);

		$count_ips = count($ips);
		for ($i = 0; $i < $count_ips; ++$i) {
			$check_value = trim($ips[$i]);
			if (!preg_match('/^(?:10|172.(?:1[6-9]|2\d|3[01])|192.168)./', $check_value)) {
				if (false !== ip2long($check_value)) {
					$return = $check_value;
					break;
				}
			}
		}
		return $return;
	}

	static public function get_user_ip() {

		$ip = false;
		if (isset($_SERVER) && isset($_SERVER["HTTP_CLIENT_IP"])) {
			$ip = $_SERVER["HTTP_CLIENT_IP"];
		}
		elseif (getenv('HTTP_CLIENT_IP')) {
			$ip = getenv('HTTP_CLIENT_IP');
		}

		if (isset($_SERVER)) {
			if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
				return self::parse_real_ip_from_xff($_SERVER["HTTP_X_FORWARDED_FOR"], $ip);
			if ($ip)
				return $ip;
			return $_SERVER["REMOTE_ADDR"];
		}

		if ($http_x_forwarder_for = getenv('HTTP_X_FORWARDED_FOR')) {
			return self::parse_real_ip_from_xff($http_x_forwarder_for, $ip);
		}

		if ($ip)
			return $ip;

		return getenv('REMOTE_ADDR');
	}

	static public function Mailer($to, $subject, $message_orig, $mimetype = "text/html", $from = "", $bcc = "", $attachments = array()) {

	}

	static public function create_unique_id() {
		$base62_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

		$value = time();
		$yield1 = "------";
		for ($i = 5; $i >= 0; $i--) {
			$yield1[$i] = $base62_chars[$value % 62];
			$value = $value / 62;
		}

		$value = posix_getpid();
		$yield2 = "------";
		for ($i = 5; $i >= 0; $i--) {
			$yield2[$i] = $base62_chars[$value % 62];
			$value = $value / 62;
		}

		list($usec, $sec) = explode(" ", microtime());
		$value = $usec * 1000000;
		$yield3 = "--";
		for ($i = 1; $i >= 0; $i--) {
			$yield3[$i] = $base62_chars[$value % 62];
			$value = $value / 62;
		}

		return $yield1.$yield2.$yield3;

	}

	static public function getBackTrace($level_to_skip = 1) {
		$stack_info = "";
		$stack = debug_backtrace();
		foreach ($stack as $key => $row) {
			if ($key <= $level_to_skip) {
				// skip few levels of backtrace
				continue;
			}
			$stack_info .= $key.": ";
			if (!isset($row['file']) && !isset($row['line'])) {
				if ($row['type'] == "->") {
					$stack_info .= "*** internal php call ***\n";
				} else {
					$stack_info .= print_r($row, 1)."\n";
				}
				continue;
			}

			$stack_info .= "File: ".$row['file'].", ";
			$stack_info .= "Line: ".$row['line'];
			$stack_info .= "\n";
		}
		return $stack_info;
	}

	static public function compose_files($files, $root_dir) {

		if (empty($files)) return '';

		foreach ($files as $ind => $file) {
			$file = realpath($root_dir.$file);
			if (empty($file) || strpos($file, $root_dir) === false) {
				unset($files[$ind]);
				continue;
			} else {
				if (file_exists($file.'-min')) {
					$files[$ind] = $file.'-min';
				} else {
					$files[$ind] = $file;
				}
			}
		}

		if (!empty($files)) {
			$ret = '';
			foreach ($files as $file) {
				$ret .= file_get_contents($file)."\n";
			}

			return $ret;
		}
	}

	static public function cssAsset($css_files) {
		global $G;

		if ($G["inst_type"] == "prod") {
			$css_link = "/css/css.php?f=".implode(",", $css_files);
			echo "<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"".$css_link."\" />";
		} else {
			foreach ($css_files as $file) {
				if (strrpos($file, ".") !== false) {
					$name = substr($file, 0, strrpos($file, "."));
					$ext = substr($file, strrpos($file, "."));
					if (file_exists(TOP_DIR.'/www/css/'.$name.'-min'.$ext)) {
						$file = $name.'-min'.$ext;
					}
				}
				echo "<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"/css/".$file."\" />\n";
			}
		}
	}

	static public function jsAsset($js_files) {
		global $G;

		if ($G["inst_type"] == "prod") {
			$js_link = "/js/js.php?f=".implode(",", $js_files);
			echo "<script type=\"text/javascript\" src=\"".$js_link."\"></script>";
		} else {
			foreach ($js_files as $file) {

				if (strrpos($file, ".") !== false) {
					$name = substr($file, 0, strrpos($file, "."));
					$ext = substr($file, strrpos($file, "."));
					if (file_exists(TOP_DIR.'/www/js/'.$name.'-min'.$ext)) {
						$file = $name.'-min'.$ext;
					}
				}
				echo "<script type=\"text/javascript\" src=\"/js/".$file."\"></script>\n";
			}
		}
	}

	static public function printIEStyles() {
		echo "
		<!--[if IE]>
		<link rel=\"stylesheet\" href=\"/css/ie.css\" type=\"text/css\" media=\"screen\" />
		<![endif]-->
		<!--[if IE 6]>
		<link rel=\"stylesheet\" href=\"/css/ie6.css\" type=\"text/css\" media=\"screen\" />
		<![endif]-->
		<!--[if IE 7]>
		<link rel=\"stylesheet\" href=\"/css/ie7.css\" type=\"text/css\" media=\"screen\" />
		<![endif]-->
		<!--[if IE 8]>
		<link rel=\"stylesheet\" href=\"/css/ie8.css\" type=\"text/css\" media=\"screen\" />
		<![endif]-->
		";
	}

	static public function stage($title = "") {
		global $G;
		array_push($G["stages"], array(
				"time" => microtime(1),
				"title" => $title
			)
		);
	}

	static public function final_stage() {
		global $G;
		self::stage();

		return;

		$start_time = $G["stages"][0]["time"];
		$end_time = $G["stages"][count($G["stages"]) -1]["time"];
		$total_time = $end_time - $start_time;

		function find_color($p) {
			$colors = array(
				0 => "#1C9218",
				20 => "#58CBDF",
				50 => "#DFC139",
				70 => "#DF0000"
			);

			$r = $colors[0];
			foreach ($colors as $v => $c) {
				if ($v > $p)
					break;
				$r = $c;
			}
			return $r;
		}

		echo "<br/>";
		echo "Served from: ".$G["hostname"]."<br/>";
		foreach ($G["stages"] as $stage_num => $stage) {
			if ($stage_num == count($G["stages"]) - 1) continue; // skip the last stage - it's just the finish
			$stage_time = $G["stages"][$stage_num + 1]["time"] - $G["stages"][$stage_num]["time"];
			$stage_percent = $stage_time / $total_time * 100;
			echo "<span style='color: ".find_color($stage_percent)."'>".$G["stages"][$stage_num]["title"]." in ".(round($stage_time, 4))." seconds (".round($stage_percent, 2)."%)</span><br/>";
		}
		echo "Total time: ".(round($total_time, 4))." seconds<br/>";
	}
}
?>